package com.ruben.simplescaffold.config;

import cn.hutool.core.lang.Opt;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.ruben.simplescaffold.handler.GlobalTimeResolver;

import java.time.LocalDateTime;

/**
 * FastJson配置
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/10/9 12:42
 */
public class FastJsonConfigHandler {

    /**
     * 配置
     */
    private static final FastJsonConfig FAST_JSON_CONFIG;

    static {
        FAST_JSON_CONFIG = new FastJsonConfig();
        // 配置序列化策略
        // ID_WORKER 生成主键太长导致 js 精度丢失
        // JavaScript 无法处理 Java 的长整型 Long 导致精度丢失，具体表现为主键最后两位永远为 0，解决思路： Long 转为 String 返回
        FAST_JSON_CONFIG.setSerializerFeatures(SerializerFeature.BrowserCompatible,
                // 处理序列化后出现$ref的坑
                SerializerFeature.DisableCircularReferenceDetect,
                // 列化枚举值为数据库存储值
                SerializerFeature.WriteEnumUsingToString);
        SerializeConfig serializeConfig = SerializeConfig.globalInstance;
        // 设置全局LocalDateTime转换
        serializeConfig.put(LocalDateTime.class, (serializer, object, fieldName, fieldType, features) -> Opt.ofNullable(object).ifPresentOrElse(obj -> serializer.out.writeString(((LocalDateTime) obj).format(GlobalTimeResolver.DATE_TIME_FORMATTER)), serializer.out::writeNull));
        FAST_JSON_CONFIG.setSerializeConfig(serializeConfig);
        ParserConfig parserConfig = ParserConfig.getGlobalInstance();
        FAST_JSON_CONFIG.setParserConfig(parserConfig);
    }

    private FastJsonConfigHandler() {
    }

    /**
     * 获取配置
     *
     * @return com.alibaba.fastjson.support.config.FastJsonConfig
     * @author <achao1441470436@gmail.com>
     * @since 2021/10/9 12:46
     */
    public static FastJsonConfig getConfig() {
        return FAST_JSON_CONFIG;
    }

}
